#include <QtGui/QApplication>
#include "wangge.h"

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include<arpa/inet.h>
#include <unistd.h>
#define MYPORT    3490 		/* 监听端口 */
#define BACKLOG 10
void *server(void *arg)
{
    wangge *w = (wangge *)arg;
     w->set_cpu("234");
    float sockfd, new_fd,numbytes; 		/* 监听端口，数据端口 */
    char buf[200];
    float  cpu;
    struct sockaddr_in my_addr; 	/* 自身的地址信息 */
    struct sockaddr_in their_addr; 	/* 连接对方的地址信息 */
    socklen_t sin_size;
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("socket");
        exit(1);
    }

    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(MYPORT); 		/* 网络字节顺序 */
    my_addr.sin_addr.s_addr = INADDR_ANY; 	/* 自动填本机IP */
    bzero(&(my_addr.sin_zero), 8); 		/* 其余部分置0 */

    if(bind(sockfd, (struct sockaddr *)&my_addr,
              sizeof(struct sockaddr)) == -1)
    {
        perror("bind");
        exit(1);
    }

    if (listen(sockfd, BACKLOG) == -1) {
        perror("listen");
        exit(1);
    }
    while(1) { 			/* 主循环 */
        sin_size = sizeof(struct sockaddr_in);
        new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
        if  (new_fd == -1) {
            perror("accept");
            continue;
        }
        printf("Got connection from %s\n",inet_ntoa(their_addr.sin_addr));
     while(1)
       {
       if ((numbytes=recv(new_fd,buf,sizeof(buf),0))==-1)
       {
        perror("recv");
       }
           cpu=atof(buf);
           w->set_cpu(buf);
           sleep(3);
       }
                printf("客户已断开\n");
               close(new_fd);
    }
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    wangge w;
    pthread_t t_id;
    pthread_create(&t_id,NULL,server,(void *)&w);
    w.show();

    return a.exec();
}
